package com.woniuxy.his.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.his.controller.form.AddGuahaoForm;
import com.woniuxy.his.entity.*;
import com.woniuxy.his.exception.AddCaseException;
import com.woniuxy.his.exception.UpdateArrangeException;
import com.woniuxy.his.mapper.*;
import com.woniuxy.his.service.IGuahaoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 挂号表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2021-08-24
 */
@Service
@Slf4j
public class GuahaoServiceImpl extends ServiceImpl<GuahaoMapper, Guahao> implements IGuahaoService {

    @Resource
    private GuahaoMapper guahaoMapper;

    @Resource
    private DoctorMapper doctorMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private ArrangeMapper arrangeMapper;

    @Resource
    private PatientMapper patientMapper;

    @Resource
    private CaseMapper caseMapper;


//    @Resource
//    private Jedis jedis;

    @Resource
    private RedissonClient redissonClient;

    public Integer addGuahao(AddGuahaoForm addGuahaoForm) {
        log.info("执行添加挂号业务");
        RBucket<Object> bucket = redissonClient.getBucket("sort");
        RBucket<Object> bu = redissonClient.getBucket("ss");
        Integer so = (Integer) bucket.get();
        bu.set(111);
        log.info("{}", bucket);
//

//        String s = jedis.get("sort");
        Double num = 0.0;
        if (Double.valueOf(so) >= 6) {
            num = Double.valueOf(so);
            num += 1;
            System.out.println(num);
            bucket.set(num);
        }


        Patient patient = new Patient();
        patient.setPatientAge(addGuahaoForm.getPatientAge());
        patient.setPatientGender(addGuahaoForm.getPatientGender());
        patient.setPatientIdCard(addGuahaoForm.getPatientIdCard());
        patient.setPatientName(addGuahaoForm.getPatientName());
        patient.setPatientTel(addGuahaoForm.getPatientTel());

        int ins = patientMapper.insert(patient);
        Integer insert;
        if (ins >= 1) {
            log.info("如果添加成功病人，继续添加挂号表和病历表");
            Guahao guahao = new Guahao();
            BeanUtils.copyProperties(addGuahaoForm, guahao);
            guahao.setStatus("待诊").setDepId(addGuahaoForm.getDepId()).setDoctorId(addGuahaoForm.getDoctorId()).setIspaid("yes");
            log.info("设置挂号状态为wait");
            QueryWrapper<Patient> wrapper = new QueryWrapper<>();
            wrapper.eq("patient_id_card", patient.getPatientIdCard());
            log.info("通过身份证号查病人id,该病人身份证为{}", patient.getPatientIdCard());
            Patient selectOne = patientMapper.selectOne(wrapper);
            guahao.setPatientId(selectOne.getPatientId());
            log.info("病人排序号为{}", num);
            guahao.setSort(num);
            log.info("添加挂号");
            insert = guahaoMapper.insert(guahao);
            if (insert != 0) {
                log.info("添加挂号成功");
                log.info("更改排班挂号数量");
                QueryWrapper<Arrange> arrangeQueryWrapper = new QueryWrapper<>();
                arrangeQueryWrapper.eq("doctor_id", guahao.getDoctorId());
                Arrange arrange = arrangeMapper.selectOne(arrangeQueryWrapper);
                if (arrange != null) {
                    log.info("如果该医生有排班，更改排班数量-1");
                    Integer arrangeNum = arrange.getArrangeNum();
                    --arrangeNum;
                    arrange.setArrangeNum(arrangeNum);
                    Integer integer = arrangeMapper.updateArrangeNumByDoctorId(arrange);
                    if (null != integer) {
                        log.info("减少排班数量成功");

                    } else {
                        throw new UpdateArrangeException("减少医生排班数量失败");
                    }

                } else {
                    throw new UpdateArrangeException("医生无排班");
                }

                log.info("开始添加病例表");
                Integer integer = caseMapper.insertCasePatientIdAndName(patient);
                if (null != integer) {
                    log.info("添加空病历表成功");
                } else {
                    throw new AddCaseException("添加空病例表失败");
                }

                return insert;
            }
        } else {
            return 0;
        }
        return 0;
    }

    public IPage findGuahaoByPage(String patientName, Integer size, Integer current) {
        log.info("执行查找挂号业务");
        log.info("业务层size{}，current{}", size, current);
        IPage page = new Page(current, size);
        IPage pageResult = guahaoMapper.findByPage(page, patientName);

        log.info("{}", pageResult);
        if (null != pageResult) {
            return pageResult;
        }
        return null;
    }

    public List<Doctor> findDoctorsByDepId(Integer depId) {
        log.info("执行根据科室id查找医生业务");
        QueryWrapper<Doctor> wrapper = new QueryWrapper<>();
        wrapper.eq("dep_id", depId);
        List<Doctor> doctors = doctorMapper.selectList(wrapper);
        if (null != doctors) {
            log.info("根据医生id查找是否排班有剩余业务");
            ArrayList<Doctor> doctorList = new ArrayList<>();
            System.out.println(doctors);
            for (Doctor d : doctors) {
                System.out.println(d.getDoctorId());
                log.info("doctor_id为{}", d.getDoctorId());
                Arrange arrange = arrangeMapper.findArrangeByDoctorId(d.getDoctorId());
                if (arrange.getArrangeNum() >= 0) {
                    log.info("如果doctor排班数量大于零");
                    doctorList.add(d);
                }
            }
            return doctorList;
        }
        return null;
    }

    public List<Department> findAllDepartment() {
        log.info("执行查找所有科室的业务");
        List<Department> departmentList = departmentMapper.findAllDepartment();
        if (null != departmentList) {
            return departmentList;
        }
        return null;
    }

    @Override//获取挂号信息，在挂号处理页面展示(GuahaoServiceImp层)
    public IPage queryInformationOfGuaHao(int current, int pageSize, int doctorId) {
        IPage page = new Page(current, pageSize);

        if (doctorId == 52) {
            IPage iPage = guahaoMapper.queryInformationOfGuaHaoBySuper(page);
            return iPage;
        } else {
            IPage iPage = guahaoMapper.queryInformationOfGuaHao(page, doctorId);
            return iPage;
        }
    }


    //添加或修改病例表数据，并修改挂号表的状态
    @Override
    public Integer modifyStatusAndSymptom(Integer guaId, String status, String symptom, String diaResult) {
        //修改挂号表的状态
        int sort1 = 100;
        int sort2 = 15;
        int sort3 = 200;//已经诊疗完毕的排最后不再考前
        int sort4 = 300;//销号的永远排在最后
        if (status.equals("挂起")) {
            Integer status1 = guahaoMapper.modifyStatus(guaId, status, sort1);
        } else if (status.equals("就诊")) {
            Integer status2 = guahaoMapper.modifyStatus(guaId, status, sort2);
        } else if (status.equals("已诊")) {
            Integer status3 = guahaoMapper.modifyStatus(guaId, status, sort3);
        } else if (status.equals("销号")) {
            Integer status4 = guahaoMapper.modifyStatus(guaId, status, sort4);
        }

        //挂号表获取病人ID
        Integer patientId = guahaoMapper.queryPatientIdByGua(guaId);


        //在病列表判断是否存在病人Id
        log.info("该病已存在，可修改数据");
        Integer symptom1 = guahaoMapper.modifySymptom(guaId, symptom, diaResult);
        return symptom1 > 0 ? 1 : 0;
    }
}
